import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { generateRoutes, filterAsyncRoutes, addAsyncRoutes } from '@/utils/dynamicRoutes'

// 基础路由（不需要权限的路由）
const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    name: 'Root',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: '/dashboard', // 重定向到仪表盘
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘' }
      },
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人中心' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
})

// 动态路由标记
let dynamicRoutesAdded = false

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 显示页面标题
  document.title = to.meta.title ? `${to.meta.title} - 管理系统` : '管理系统'

  // 检查是否需要登录
  if (to.path === '/login') {
    if (authStore.isLoggedIn) {
      next('/')
    } else {
      next()
    }
    return
  }

  // 检查是否已登录
  if (!authStore.isLoggedIn) {
    next('/login')
    return
  }

  // 检查是否已添加动态路由
  if (!dynamicRoutesAdded) {
    try {


      // 如果用户菜单为空，重新获取
      if (authStore.userMenus.length === 0) {
        await authStore.fetchUserMenus()
      }

      // 生成动态路由
      const asyncRoutes = generateRoutes(authStore.userMenus)

      const filteredRoutes = filterAsyncRoutes(asyncRoutes, authStore.userPermissions)

      // 添加动态路由
      addAsyncRoutes(router, filteredRoutes)
      dynamicRoutesAdded = true

      // 判断是否存在目标路由
      const targetRoute = router.getRoutes().find(route => route.path === to.path)

      // 如果目标路由存在，直接导航
      if (targetRoute) {
        next(to)
      } else {
        // 如果目标路由不存在，检查是否是菜单中定义的路由
        const menuRoute = authStore.userMenus.find(menu => menu.path === to.path && menu.type !== 3)
        if (menuRoute) {
          // 如果是菜单中定义的路由，等待路由完全加载后重试
          setTimeout(() => {
            next(to)
          }, 100)
        } else {
          // 如果不是菜单中定义的路由，跳转到仪表盘
          next('/dashboard')
        }
      }
    } catch (error) {
      next('/login')
    }
  } else {
    // 检查页面权限
    if (to.meta.permission && !authStore.hasPermission(to.meta.permission)) {
      next('/404')
    } else {
      next()
    }
  }
})

// 重置路由方法
export const resetRouter = () => {
  const newRouter = createRouter({
    history: createWebHistory(),
    routes: constantRoutes
  })
  router.matcher = newRouter.matcher
  dynamicRoutesAdded = false
}

export default router